<template>
  <div class="dashboard-container">
    <!-- 提示词 -->
    <!-- 学生信息 -->
    <div>
      <el-container>
        <el-main>
          <div align="center" height="100px" style="margin:20px">
            <el-avatar :size="100" :src="info.avatar"> avatar </el-avatar>
          </div>
          <e-desc margin='0 12px' label-width='100px'>
            <e-desc-item label="姓名">{{info.name}}</e-desc-item>
            <e-desc-item label="年龄">{{ info.age }}岁</e-desc-item>
            <e-desc-item label="性别">{{ info.sex==1?'男':'女' }}</e-desc-item>
            <e-desc-item label="学号">{{info.number}}</e-desc-item>
            <e-desc-item label="手机号">{{info.phone}}</e-desc-item>
            <!-- <e-desc-item label="操作" :span='3'>
              <template>
                <el-button size="small" type="primary">修改</el-button>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </e-desc-item> -->
          </e-desc>

        </el-main>
      </el-container>
    </div>
    <div v-show="!isRegisterFace">
      <div class="dashboard-text">
        {{ name }}同学，你还未进行人脸注册，可能会影响你的考试，请尽快注册！！
      </div>
      <div class="button">
        <el-button @click="registerFace()">人脸注册</el-button>
        <el-button @click="updateFace()">人脸更新</el-button>
        <el-button @click="checkFace()">考试人脸检验</el-button>
        <el-button @click="checkFaceNormal()">平时人脸检验</el-button>
      </div>
    </div>

    <div class="button">
        <el-button @click="updateFace()">人脸更新</el-button>
        <el-button @click="checkFace()">考试人脸检验</el-button>
        <el-button @click="checkFaceNormal()">平时人脸检验</el-button>
    </div>
    <div class="camera_outer">
        <video
          id="videoCamera"
          :width="videoWidth"
          :height="videoHeight"
          autoplay
        ></video>
        <canvas
          style="display: none"
          id="canvasCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></canvas>
        <div v-if="imgSrc" class="img_bg_camera">
          <p>效果预览</p>
          <img :src="imgSrc" alt class="tx_img" />
        </div>
    </div>

  </div>
</template>

<script>
import {getInfo, shangchuanPhoto, updatePhoto, checkPhotoForExam,checkPhotoNormal } from "@/api/user";
import { mapGetters } from "vuex";

import eDesc from "./component/eDesc.vue";
import EDescItem from "./component/eDescItem.vue"
export default {
  name: "Dashboard",
  components:{
    eDesc,
    EDescItem
  },
  data() {
    return {
      token:'',
      info:null,
      videoWidth: 400,
      videoHeight: 350,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo: false,
    };
  },
  computed: {
    //从vuex中拿到公共数据，注意名字
    ...mapGetters(["name", "isRegisterFace"]),
  },
  mounted() {
    //this.getCompetence()//进入页面就调用摄像头
    this.token =  this.$store.getters.token;
    this.getInfo()
  },
  methods: {
    async getInfo(){
      let result =
        await getInfo(this.token);
      if (result.code == 20000) {
          this.info = result.data.student;
      }
    },
    //人脸注册
    registerFace() {
      this.getCompetence();
      setTimeout(this.setImage(), 2000);
    },
    updateFace(){//更新和注册相同，只有底层调用的接口不同
      this.getCompetence();
      setTimeout(this.setImage2(), 2000);
    },
    checkFace(){//人脸检验--考试
      this.getCompetence();
      setTimeout(this.setImage3(), 2000);      
    },
    checkFaceNormal()//人脸检验，平时
    {
      this.getCompetence();
      setTimeout(this.setImage4(), 2000);
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = "block";
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            //不存在则报错
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //  绘制图片（拍照功能）
    async setImage() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image; //赋值并预览图片
      let result = await shangchuanPhoto(image, { emulateJSON: true });
      if (result.code == 20000) {
        this.$store.dispatch('user/getInfo');
      }
    },
    async setImage2() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image; //赋值并预览图片
      let result = await updatePhoto(image, { emulateJSON: true });
      if (result.code == 20000) {
        this.$store.dispatch('user/getInfo');
      }
    },
    async setImage3() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image; //赋值并预览图片
      let result = await checkPhotoForExam(image, { emulateJSON: true });
      // if (result.code == 20000) {
      //   //成功的画不会弹出消息
      // }
      if(result.code == 1){
        alert("未识别到人脸");
      }
      else if(result.code == 2){
        alert("检验到多张人脸，无关人员请离开");
      }
      else if(result.code == 3){
        alert("识别错误！");//可以采用三次识别错误就终止考试的方式
      }
  
    },
    async setImage4() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image; //赋值并预览图片
      let result = await checkPhotoNormal(image, { emulateJSON: true });
      
      if (result.code == 20000) {
        alert("认证成功");
      }
      else{
        alert("识别错误！请重新检测或更新人脸信息");
      }
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
    // base64转文件，此处没用到
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.getface {
  position: absolute;
  top: 20%;
  left: 35%;
}
</style>
